package com.dms.modules.merchant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dms.common.api.ApiResponse;
import com.dms.common.api.ApiResponseCode;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.JwtTokenProvider;
import com.dms.common.utils.FileUploadUtils;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.product.dto.ProductDTO;
import com.dms.modules.product.dto.ProductSearchDTO;
import com.dms.modules.product.dto.ProductSkuDTO;
import com.dms.modules.product.dto.ProductSpecDTO;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductSpecTemplate;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.product.vo.ProductDetailVO;
import com.dms.modules.product.entity.ProductCategory;
import com.dms.modules.product.service.ProductCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.NotEmpty;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dms.modules.merchant.dto.MerchantLoginRequest;
import com.dms.modules.merchant.dto.ShopUpdateDTO;
import com.dms.modules.merchant.vo.ShopInfoVO;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.service.MerchantService;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.dms.modules.merchant.dto.MerchantLoginResponse;
import com.dms.modules.merchant.dto.MerchantCreateDTO;
import com.dms.modules.product.service.ProductSpecTemplateService;
import com.dms.modules.merchant.service.MerchantAuthService;
import com.dms.modules.merchant.vo.MerchantShopVO;
import com.dms.modules.user.entity.User;
import com.dms.modules.user.mapper.UserMapper;

@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/merchant")
@Api(tags = "商家接口")
public class MerchantController {

    @Autowired
    private ProductService productService;

    @Autowired
    private ProductCategoryService categoryService;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ProductSpecTemplateService productSpecTemplateService;

    @Autowired
    private MerchantAuthService merchantAuthService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取当前登录用户ID
     */
    private Long getUserId() {
        return SecurityUtils.getCurrentUserId();
    }

    /**
     * 将IPage转换为Page
     */
    private <T> Page<T> convertToPage(IPage<T> iPage) {
        Page<T> page = new Page<>();
        page.setRecords(iPage.getRecords());
        page.setTotal(iPage.getTotal());
        page.setSize(iPage.getSize());
        page.setCurrent(iPage.getCurrent());
        return page;
    }

    // ==================== 需要认证的接口 ====================

    @GetMapping("/shop")
    @ApiOperation("获取店铺信息")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<MerchantShopVO> getShopInfo() {
        Long userId = getUserId();
        // 通过userId获取商家信息
        Merchant merchant = merchantService.getByUserId(userId);
        if (merchant == null) {
            throw new BusinessException("商家信息不存在");
        }
        return ApiResponse.success(merchantService.getShopInfo(merchant.getId()));
    }

    @PostMapping("/shop/logo")
    @ApiOperation("上传店铺logo")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<String> uploadShopLogo(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ApiResponse.businessFailed("请选择要上传的文件");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ApiResponse.businessFailed("只能上传图片文件");
            }

            // 获取文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";

            // 生成OSS存储路径
            String path = "merchant/logo/" + getUserId() + "/" + System.currentTimeMillis() + suffix;

            // 上传文件到OSS并返回URL
            String url = fileUploadUtils.uploadFile(file, path);
            return ApiResponse.success(url);
            
        } catch (Exception e) {
            log.error("上传店铺logo失败", e);
            return ApiResponse.businessFailed("上传失败：" + e.getMessage());
        }
    }

    @PutMapping("/shop")
    @ApiOperation("更新店铺信息")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Void> updateShopInfo(@RequestBody @Validated ShopUpdateDTO updateDTO) {
        Long userId = getUserId();
        // 通过userId获取商家信息
        Merchant merchant = merchantService.getByUserId(userId);
        if (merchant == null) {
            throw new BusinessException("商家信息不存在");
        }
        
        // 更新商家信息
        merchant.setShopName(updateDTO.getShopName());
        merchant.setShopLogo(updateDTO.getShopLogo());
        merchant.setShopDescription(updateDTO.getShopDescription());
        merchant.setNotice(updateDTO.getNotice());
        merchant.setBusinessHours(updateDTO.getBusinessHours());
        merchant.setContactPhone(updateDTO.getContactPhone());
        merchant.setContactEmail(updateDTO.getContactEmail());
        merchant.setAddress(updateDTO.getAddress());
        merchant.setAfterSalePolicy(updateDTO.getAfterSalePolicy());
        merchant.setBusinessLicense(updateDTO.getBusinessLicense());
        merchant.setBusinessLicenseImage(updateDTO.getBusinessLicenseImage());
        merchant.setLegalPerson(updateDTO.getLegalPerson());
        merchant.setLegalPersonIdCard(updateDTO.getLegalPersonIdCard());
        merchant.setLegalPersonIdCardFront(updateDTO.getLegalPersonIdCardFront());
        merchant.setLegalPersonIdCardBack(updateDTO.getLegalPersonIdCardBack());
        
        merchantService.updateById(merchant);
        return ApiResponse.success();
    }

    @GetMapping("/tree")
    @ApiOperation("获取分类树")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<List<ProductCategory>> getCategoryTree() {
        log.info("获取分类树");
        return ApiResponse.success(categoryService.getCategoryTree());
    }

    @GetMapping("/children/{parentId}")
    @ApiOperation("获取子分类列表")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<List<ProductCategory>> getChildren(
            @ApiParam("父分类ID") @PathVariable Long parentId) {
        log.info("获取子分类: parentId={}", parentId);
        return ApiResponse.success(categoryService.getCategoryList(parentId));
    }

    // ==================== 商品规格相关接口 ====================

    @GetMapping("/specs")
    @ApiOperation("获取商家规格列表")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<List<ProductSpecTemplate>> getMerchantSpecs() {
        try {
            List<ProductSpecTemplate> specs = productSpecTemplateService.list();
            return ApiResponse.success(specs);
        } catch (Exception e) {
            log.error("获取商家规格列表失败", e);
            return ApiResponse.businessFailed("获取商家规格列表失败");
        }
    }


    @PostMapping("/specs")
    @ApiOperation("创建商家规格")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Long> createMerchantSpec(@RequestBody @Validated ProductSpecDTO specDTO) {
        try {
            Long id = productSpecTemplateService.saveSpecTemplate(specDTO);
            return ApiResponse.success(id);
        } catch (Exception e) {
            log.error("创建商家规格失败", e);
            return ApiResponse.businessFailed("创建商家规格失败");
        }
    }

    @PutMapping("/specs/{id}")
    @ApiOperation("更新商家规格")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Void> updateMerchantSpec(@PathVariable Long id, @RequestBody @Validated ProductSpecDTO specDTO) {
        try {
            specDTO.setId(id);
            productSpecTemplateService.updateSpecTemplate(specDTO);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("更新商家规格失败", e);
            return ApiResponse.businessFailed("更新商家规格失败");
        }
    }

    @DeleteMapping("/specs/{id}")
    @ApiOperation("删除商家规格")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<Void> deleteMerchantSpec(@PathVariable @NotNull(message = "规格ID不能为空") Long id) {
        try {
            productSpecTemplateService.deleteSpecTemplate(id);
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("删除商家规格失败", e);
            return ApiResponse.businessFailed("删除商家规格失败");
        }
    }

    @GetMapping("/specs/categories/{categoryId}")
    @ApiOperation("获取分类下的规格列表")
    @PreAuthorize("hasRole('MERCHANT')")
    public ApiResponse<List<ProductSpecTemplate>> getSpecsByCategory(
            @PathVariable @NotNull(message = "分类ID不能为空") Long categoryId) {
        try {
            List<ProductSpecTemplate> specs = productSpecTemplateService.listByCategoryId(categoryId);
            return ApiResponse.success(specs);
        } catch (Exception e) {
            log.error("获取分类规格列表失败", e);
            return ApiResponse.businessFailed("获取分类规格列表失败");
        }
    }
} 

